/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import { ProjectBuildProfile } from '../../options/build/project-build-profile.js';
import { sendSocketRequest, MessageType, SocketRequest } from '../java-daemon/websocket.js';

import SigningConfigBuildOpt = ProjectBuildProfile.SigningConfigBuildOpt;

export interface SignParams {
  mode: string;
  keyAlias: string;
  keyPwd: string;
  appCertFile: string;
  profileFile?: string;
  profileSigned?: number;
  inForm?: string; // zip  elf  bin 默认 zip
  signAlg: string;
  keystoreFile: string;
  keystorePwd: string;
  signCode?: number;
  inFile: string;
  outFile: string;
}

export interface HarSignParams {
  keyAlias: string;
  keyPwd: string;
  signCertFile: string;
  profileFile?: string;
  inForm?: string;
  inFileForm?: string;
  signAlg: string;
  keystoreFile: string;
  keystorePwd: string;
  inFile: string;
}

export interface VerifyProfileParams {
  inFile: string;
  outFile: string;
}

export async function sendSignRequest(signToolJarPath: string, signParams: SignParams) {
  const signRequest: SocketRequest = {
    type: MessageType.SIGN_APP,
    data: JSON.stringify(signParams),
  };
  return sendSocketRequest(signRequest, signToolJarPath);
}

export async function sendSignHarRequest(signToolJarPath: string, signParams: HarSignParams) {
  const signRequest: SocketRequest = {
    type: MessageType.SIGN_SDK,
    data: JSON.stringify(signParams),
  };
  return sendSocketRequest(signRequest, signToolJarPath);
}

export async function sendVerifyProfileRequest(signToolJarPath: string, verifyProfileParams: VerifyProfileParams) {
  const signRequest: SocketRequest = {
    type: MessageType.VERIFY_PROFILE,
    data: JSON.stringify(verifyProfileParams),
  };
  return sendSocketRequest(signRequest, signToolJarPath);
}

export function constructSignParams(
  signingConfig: SigningConfigBuildOpt,
  inFile: string,
  outFile: string,
  keystorePwd: string,
  keyPwd: string,
  inForm: string,
  mode = 'localSign',
) {
  const signRequest: SignParams = {
    mode,
    keystoreFile: signingConfig.material.storeFile,
    keystorePwd,
    keyAlias: signingConfig.material.keyAlias,
    keyPwd,
    signAlg: signingConfig.material.signAlg,
    profileFile: signingConfig.material.profile,
    appCertFile: signingConfig.material.certpath,
    inForm,
    inFile,
    outFile,
  };
  return signRequest;
}

export function constructHarSignParams(signingConfig: SigningConfigBuildOpt, inFile: string, outFile: string, keystorePwd: string, keyPwd: string) {
  const signRequest: HarSignParams = {
    keystoreFile: signingConfig.material.storeFile,
    keystorePwd,
    keyAlias: signingConfig.material.keyAlias,
    keyPwd,
    inFileForm: 'DIR',
    signAlg: signingConfig.material.signAlg,
    profileFile: signingConfig.material.profile,
    signCertFile: signingConfig.material.certpath,
    inFile,
  };
  return signRequest;
}
